package com.alpha.servlets;

import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import javax.naming.NamingException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;

import com.alpha.bom.Answer;
import com.alpha.bom.Exam;
import com.alpha.bom.ExamResponse;
import com.alpha.bom.Professor;
import com.alpha.bom.Question;
import com.alpha.bom.RealExam;
import com.alpha.bom.Student;
import com.alpha.dao.AnswerDao;
import com.alpha.dao.ExamDao;
import com.alpha.dao.ExamResponseDao;
import com.alpha.dao.QuestionDao;

/**
 * Servlet implementation class TakeExamServlet
 */
@WebServlet("/TakeExamServlet")
public class TakeExamServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	private static Logger logger = Logger.getLogger(TakeExamServlet.class.getName());
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public TakeExamServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		logger.info(this.getClass().getSimpleName()+" get method started.");
		
		int examId = 0;
		Student student = null;
		Exam exam = null;
		ExamResponse examResponse = null;
		
		HttpSession session = request.getSession();
		
		//Do not allow a professor to access this
		if(session.getAttribute("user")!=null && (session.getAttribute("user") instanceof Professor)){
			response.sendRedirect("403.jsp");
			return;
		}
		
		//student is either the Student user or a null public user
		if(session.getAttribute("user")!=null && (session.getAttribute("user") instanceof Student)){
			student = (Student) session.getAttribute("user");
		}
	
		//get parameter exam id
		if(request.getParameter("exam_id")!=null){
			examId = Integer.parseInt(request.getParameter("exam_id"));
		} else {
			if(student!=null){
				response.sendRedirect("MyExamServlet?error=Exam+not+found.");
				return;
			} else {
				response.sendRedirect("PracticeExamServlet?error=Exam+not+found.");	
				return;
			}
		}

		ExamDao eDao = new ExamDao();
		QuestionDao qDao = new QuestionDao();
		AnswerDao aDao = new AnswerDao();

		try {
			//get exam from exam dao
			exam = eDao.retrieveExamById(examId);
			
			//get questions for this exam from question dao
			//randomize questions
			ArrayList<Question> tempQ = qDao.retrieveQuestions(exam.getExamId());
			Collections.shuffle(tempQ);
			exam.setQuestions(tempQ);
			
			//get answer choices for every question
			for(Question q:exam.getQuestions()){
				ArrayList<Answer> tempC = aDao.retrieveChoices(q.getQuestionId());
				Collections.shuffle(tempC);
				q.setChoices(tempC);
			}	
		} catch (Exception e) {
			if(student!=null){
				logger.error(e.getMessage());
				response.sendRedirect("MyExamServlet?error=Exam+not+found.");
				return;
			} else {
				logger.error(e.getMessage());
				response.sendRedirect("PracticeExamsServlet?error=Exam+not+found.");	
				return;
			}
		} 	
		
		//create a new examresponse object with given exam and student
		examResponse = new ExamResponse(exam, student);
		session.setAttribute("exam_response", examResponse);
				
		//forward and pass the examresponse object
		//forward and pass question object of the very first question to takeexamjsp
		//add parameter question_index
		request.setAttribute("question", exam.getQuestions().get(0));
		RequestDispatcher dis = request.getRequestDispatcher("TakeExam.jsp?=0");
		dis.forward(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		logger.info(this.getClass().getSimpleName()+" post method started.");
		
		ExamResponse examResponse = null;
		int nextQuestionIndex = 0;
		int questionId = 0;
		int answerId = 0;
		Question question = null;
		Answer answer = null;
		Student student = null;
		
		HttpSession session = request.getSession();
		
		//Do not allow a professor to access this
		if(session.getAttribute("user")!=null && (session.getAttribute("user") instanceof Professor)){
			response.sendRedirect("403.jsp");
			return;
		}
		
		if(session.getAttribute("user")!=null && (session.getAttribute("user") instanceof Student)){
			student = (Student) session.getAttribute("user");
		}
		
		//get examresponse object from session
		if(session.getAttribute("exam_response")!=null){
			examResponse = (ExamResponse) session.getAttribute("exam_response");
		} else {
			if(student!=null){
				response.sendRedirect("MyExamServlet?error=Session+time+out.");
				return;
			} else {
				response.sendRedirect("PracticeExamsServlet?error=Session+time+out.");	
				return;
			}
		}
		
		//receive next question index
		if(request.getParameter("next_question_index")!=null){
			nextQuestionIndex = Integer.parseInt(request.getParameter("next_question_index"));
		}
		
		//receive answer id and get answer from dao
		//receive question id and get question from dao
		if(request.getParameter("answer_id")!=null){
			answerId = Integer.parseInt(request.getParameter("answer_id"));
		}
		if(request.getParameter("question_id")!=null){
			questionId = Integer.parseInt(request.getParameter("question_id"));
		}
		AnswerDao aDao = new AnswerDao();
		QuestionDao qDao = new QuestionDao();
		try {
			answer = aDao.retrieveAnswer(answerId);
		} catch (NamingException e1) {
			logger.error(e1.getMessage());
			return;
		} catch (SQLException e1) {
			logger.error(e1.getMessage());
			return;
		}
		try {
			question = qDao.retrieveQuestion(questionId);
		} catch (Exception e) {
			if(session.getAttribute("user")!=null && (session.getAttribute("user") instanceof Student)){
				logger.error(e.getMessage());
				response.sendRedirect("MyExamServlet?error=Question+not+found.");
				return;
			} else {
				logger.error(e.getMessage());
				response.sendRedirect("PracticeExamsServlet?error=Question+not+found.");	
				return;
			}
		}
		
		boolean updateAnswer = false;
		
		//put in exam response object's tree map the question and answer
		if(examResponse.getAnswers().get(question)!=null){
			updateAnswer = true;
		}
		examResponse.addAnswer(question, answer);
		
		//if student!=null,
		//			insert in DB tbl_student_response the answer, question, student
		if(student!=null && ("Real".equals(examResponse.getExam().getExamType()))){
			ExamResponseDao erDao = new ExamResponseDao();
			try {
				if(answer!=null){
					if(updateAnswer){
						erDao.updateExamResponse(student.getUserId(), examResponse.getExam().getExamId(), answer.getAnswerId(), question.getQuestionId());
					} else {
						erDao.insertExamResponse(student.getUserId(), examResponse.getExam().getExamId(), answer.getAnswerId(), question.getQuestionId());
					}
				}
			} catch (Exception e) {
				if(session.getAttribute("user")!=null && (session.getAttribute("user") instanceof Student)){
					logger.error(e.getMessage());
					response.sendRedirect("MyExamServlet?error=Database+error.");
					return;
				} else {
					logger.error(e.getMessage());
					response.sendRedirect("PracticeExamsServlet?error=Database+error.");	
					return;
				}
			}
		}
		
		//end the exam if exam is already deactivated by the professor
		ExamDao eDao = new ExamDao();
		Exam tempExam;
		try {
			tempExam = eDao.retrieveExamById(examResponse.getExam().getExamId());
			if("Real".equals(tempExam.getExamType()) && student!=null){
				if(((RealExam)tempExam).isLocked()){
					ExamResponseDao erDao = new ExamResponseDao();
					try {
						erDao.updateDateTaken(examResponse.getExam().getExamId(), student.getUserId(), new Date());
					} catch (NamingException e) {
						logger.error(e.getMessage());
						return;
					} catch (SQLException e) {
						logger.error(e.getMessage());
						return;
					}
					examResponse.setComplete(true);	
					session.removeAttribute("exam_response");
					request.setAttribute("exam_response", examResponse);
					RequestDispatcher dispatcher = request.getRequestDispatcher("StudentResponse.jsp?error=Sorry,+the+exam+is+already+deactivated.");
					dispatcher.forward(request, response);
					return;
				}
			}
		} catch (Exception e) {
			logger.error(e.getMessage());
			return;
		}
		
		if("End Exam".equalsIgnoreCase(request.getParameter("submit_button")) || "Back to Review".equalsIgnoreCase(request.getParameter("submit_button"))){
			response.sendRedirect("ReviewExam.jsp");
			return;
		}
		
		//if examresponse.getexam.getquestions.get(next question index) exists,
		//			forward and pass examresponse object, next question object, and next question index
		//else,
		//			forward to ReviewExamServlet forward examresponse object "exam_response"
		if((nextQuestionIndex >=0) && (nextQuestionIndex < examResponse.getExam().getQuestions().size())){
			request.setAttribute("question", examResponse.getExam().getQuestions().get(nextQuestionIndex));
			RequestDispatcher dis = request.getRequestDispatcher("TakeExam.jsp?q_index="+nextQuestionIndex);
			dis.forward(request, response);
			return;
		} else {
			response.sendRedirect("ReviewExam.jsp");
			return;
		}
		
	}

}
